'use strict'
const { Product, Op } = require('../moudl')
let fn_product_list = async(ctx, next) => {

    let keyword = ctx.request.query.keyword || ''

    if (keyword) {

        let list = await Product.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { head: keyword },
                    { digest: keyword },
                    { details: keyword },
                    { classify: keyword },
                    { anthour: keyword },
                    
                    
                ]
            },
            order: ['id']
        })
        ctx.body = list;
    } else {
        let list = await Product.findAll({
            order: ['id']
        })
        ctx.body = list
    }
}
let fn_product_id = async(ctx, next) => {
    let id = ctx.request.params.id;
    let list = await Product.findAll({
        where: {
            id: id
        }
    })
    ctx.body = list
}
let fn_post = async(ctx, next) => {
    let data = ctx.request.body;
    await Product.create({
         head: data.head,
         digest: data.digest, 
         details: data.details, 
         classifly: data.classify, 
         anthour: data.anthour,
         

    })
    let arr = await Product.findAll()
    ctx.body = arr
}
let fn_put = async(ctx, next) => {
    let id = ctx.request.params.id;
    let data = ctx.request.body;
    

    await Product.update({
         head: data.head,
         digest: data.digest, 
         details: data.details, 
         classifly: data.classify, 
         anthour: data.anthour,
         
    }, {
        where: {
            id: id
        }
    })
    let arr = await Product.findAll()
    ctx.body = arr

}
let fn_delete = async(ctx, next) => {
    let id = ctx.request.params.id;

    await Product.destroy({
        where: {
            id: id
        }
    })
    ctx.body = id
}

module.exports = {
    'get /product': fn_product_list,
    'get /product/:id': fn_product_id,
    'post /product': fn_post,
    'put /product/:id': fn_put,
    'delete /product/:id': fn_delete
}